package com.synjones.pay.web.biz.recharge.controller;

import com.synjones.core.util.Charsets;
import com.synjones.core.util.MapUtil;
import com.synjones.core.util.RequestUtil;
import com.synjones.pay.model.common.CommonConstant;
import com.synjones.pay.model.context.StatusInfo;
import com.synjones.pay.model.recharge.RechargeReqBean;
import com.synjones.pay.model.recharge.RechargeRespBean;
import com.synjones.pay.web.biz.common.FailedVO;
import com.synjones.pay.web.biz.common.PageParams;
import static com.synjones.pay.web.biz.common.PageParams.AUTOMATIC_PAGE;
import static com.synjones.pay.web.biz.common.PageParams.FAILED_PAGE;
import static com.synjones.pay.web.biz.common.PageParams.FORM_METHOD;
import static com.synjones.pay.web.biz.common.PageParams.PAY_COMMON_RESPONSES;
import static com.synjones.pay.web.biz.common.PageParams.POST;
import static com.synjones.pay.web.biz.common.PageParams.RECHARGE_PAGE;
import static com.synjones.pay.web.biz.common.PageParams.SUCCESS_PAGE;
import static com.synjones.pay.web.biz.common.PageParams.USER_AGENT;
import com.synjones.pay.web.biz.common.ReqDataItemName;
import static com.synjones.pay.web.biz.common.ReqDataItemName.DEVICE;
import com.synjones.pay.web.biz.common.WxResponseBean;
import static com.synjones.pay.web.biz.common.WxResponseBean.assemErrorWxRespBean;
import com.synjones.pay.web.biz.recharge.helper.RechargeHelperBean;
import com.synjones.pay.web.biz.recharge.service.IRechargeService;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 电子账户充值
 *
 * @author sxj
 */
@Controller
@RequestMapping("/m")
public class RechargeController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RechargeController.class);
    @Resource
    private IRechargeService rechargeService;

    /**
     * 给电子账户充值入口
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = ("/recharge"), produces = ("text/plain;charset=UTF-8"))
    public String recharge(HttpServletRequest request, HttpSession session) {
        Map<String, String> map = RequestUtil.getParameterMap(request);
        map.put(DEVICE, request.getHeader(USER_AGENT));//从浏览器中获取设备信息
        LOGGER.info("充值业务系统接收的参数为：{}", MapUtil.toQueryString(map, false, Charsets.UTF_8.name()));
        //签名验证 TODO
        ///////////////
        session.setAttribute(session.getId(), map);
        return "redirect:dispRecharge";
    }

    /**
     * 跳转到充值页面
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("/dispRecharge")
    public String toRechargePage(HttpServletRequest request, HttpSession session) {
        Map<String, String> map = (Map<String, String>) session.getAttribute(session.getId());
        session.removeAttribute(session.getId());
        LOGGER.info("从session中获取到的充值业务参数为：{}", MapUtil.toQueryString(map, false, Charsets.UTF_8.name()));
        FailedVO failedVO;
        if (map != null) {
            WxResponseBean respBean = rechargeService.getRechargeCardInfo(map.get(ReqDataItemName.REQ_ID));
            if (StatusInfo._0000.code().equals(respBean.getErrCode())) {
                RechargeReqBean rrb = RechargeHelperBean.getRechargeReqBean(respBean,map.get(ReqDataItemName.APP_ID),map.get(DEVICE));
                session.setAttribute(session.getId(), rrb);
                return RECHARGE_PAGE;
            }
            failedVO = RechargeHelperBean.getRechargeFailedVO(assemErrorWxRespBean(respBean));
        } else {
            LOGGER.info("req_id不能为空");
            failedVO = new FailedVO(StatusInfo._9000.code(), "请求者id不能为空");
        }
        request.setAttribute(PageParams.FAILED_VO, failedVO);
        return FAILED_PAGE;
    }

    /**
     * 提交充值信息
     *
     * @param request
     * @param amount
     * @param session
     * @return
     */
    @RequestMapping("/doRecharge")
    public String sureRecharge(HttpServletRequest request, String amount, HttpSession session) {
        RechargeReqBean rechargeReq = (RechargeReqBean) session.getAttribute(session.getId());
        session.removeAttribute(session.getId());
        FailedVO failedVO;
        if (rechargeReq != null) {
            rechargeReq.setAmount(amount);//设置充值金额
            RechargeRespBean rrb = rechargeService.getRechargeRespBean(rechargeReq);
            if (StatusInfo._0000.code().equals(rrb.getStatusCode())) {//成功时,直接跳转到金智的付款页面，参数已经传递过了，直接跳转页面即可
                request.setAttribute(CommonConstant.JUMPL_URL, rrb.getRespMap().get(CommonConstant.JUMPL_URL));
                request.setAttribute(FORM_METHOD, POST);
                return AUTOMATIC_PAGE;
            }
            failedVO = RechargeHelperBean.getChargeFailedVO(rrb);
        } else {
            LOGGER.info("充值请求参数不能为空");
            failedVO = new FailedVO(StatusInfo._9000.code(), "未知请求");
        }
        request.setAttribute(PageParams.FAILED_VO, failedVO);
        return FAILED_PAGE;
    }

    /**
     * 接受充值返回结果 页面通知类型，由金智调用此接口，
     *
     * @param request
     * @return
     */
    @RequestMapping("recWisPage")
    public String receiveWisPage(HttpServletRequest request) {
        Map<String, String> map = RequestUtil.getParameterMap(request);
        //TODO 此map是否会为空，如果为空，还得处理
        LOGGER.info("金智充值成功后页面通知参数为：【{}】", MapUtil.toQueryString(map, false, Charsets.UTF_8.name()));
        RechargeRespBean rrb = rechargeService.recRechargeRespBean(map);
        if (StatusInfo._0000.code().equals(rrb.getStatusCode())) {
            request.setAttribute(PAY_COMMON_RESPONSES, rrb);
            return SUCCESS_PAGE;
        }
        request.setAttribute(PageParams.FAILED_VO, RechargeHelperBean.getChargeFailedVO(rrb));
        return FAILED_PAGE;
    }

    @RequestMapping("/test/rechange")
    public String test2() {
        return RECHARGE_PAGE;
    }

}
